package com.smartlight.godlight;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.nfc.Tag;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.target.Target;
import com.bumptech.glide.request.transition.Transition;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.smartlight.godlight.constant.GodlApi;
import com.smartlight.godlight.model.AppInfo;
import com.smartlight.godlight.utils.OkHttpUtils;
import com.smartlight.godlight.utils.SharedPreferencesUtils;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {
    private final String TAG = "MainActivity";


    // Used to load the 'jnidemo' library on application startup.
    static {
        System.loadLibrary("jnidemo");
    }

    protected SerialPort mSerialPort = null;
    private int uartBaudrate = 9600;
    private String uartPort = "/dev/ttyS1";//ttyMT1 //ttyS1

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_layout);

        // 点击时间
        Button btn_worship_start = findViewById(R.id.btn_worship_start);
        btn_worship_start.setOnClickListener(v -> {
            Intent intent = new Intent();
            intent.setClass(MainActivity.this,WorshipData.class);
            startActivity(intent);
        });

        // 点击设置按钮
        ImageView settingImageview = findViewById(R.id.settingImageview);
        settingImageview.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(MainActivity.this, SettingActivity.class);
                startActivity(intent);
            }
        });


        Log.d(TAG, "本地缓存的接口数据: " + SharedPreferencesUtils.getParam(MainActivity.this, "appInfo", ""));

        if(SharedPreferencesUtils.getParam(MainActivity.this, "appInfo", "") == ""){
            // api请求初始化
            fetchData();
        }else{
            // 设置标题
            setTitle();
            // 设置背景图片
            setBg();
        }

        // JNI code
        try {
            if (mSerialPort == null) {
                mSerialPort = new SerialPort(new File(uartPort), uartBaudrate, 0);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
//        SendMessage(5, "guige", 88, "发发发", 1, 1);
//        SendCmdInitSubBoardID(1, 500);
//        SendCmdAllLightCtrl(1);
//        SendCmdClearSingle(88);

    }

    private void setTitle() {
        if (SharedPreferencesUtils.getParam(this,"title", "") != ""){
            TextView title = findViewById(R.id.title);
            title.setText(SharedPreferencesUtils.getParam(this,"title", "").toString());
        }
    }

    private void setBg() {
        String imgUrl = null;
        if (SharedPreferencesUtils.getParam(this,"backgroundUrl", "") != ""){
            Log.d(TAG, "背景图片： " + GodlApi.BASEURL + SharedPreferencesUtils.getParam(this,"backgroundUrl", ""));
            imgUrl = GodlApi.BASEURL + SharedPreferencesUtils.getParam(this,"backgroundUrl", "");
        }
        ImageView bgImageView = findViewById(R.id.bgImageview);
        Glide.with(MainActivity.this)
                .load(imgUrl)
                .apply(new RequestOptions().diskCacheStrategy(DiskCacheStrategy.ALL)) // 设置缓存策略，这里是缓存源资源和结果图像到磁盘缓存中
                .timeout(20000) // 设置超时时间为20秒
                .into(bgImageView);

    }

    /**
     * Request Data
     */
    private void fetchData() {
        OkHttpUtils.get(GodlApi.GET_APP_INFO, new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                GodlApi.printLog(TAG, "接口: " + GodlApi.GET_APP_INFO +  ", 请求失败" + e.toString());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this, "网络异常，请求失败，请重试！", Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String data = response.body().string();
                GodlApi.printLog(TAG, "接口: " + GodlApi.GET_APP_INFO +  ", 请求成功，返回数据:" + data);

                try{
                    // 解析数据
                    JsonObject jsonObject = new Gson().fromJson(data, JsonObject.class);
                    Log.d(TAG, "----解析数据，读取数据data---" + jsonObject.get("data").toString());
                    AppInfo appInfo = new Gson().fromJson(jsonObject.get("data").toString(), AppInfo.class);
                    Log.d(TAG, "----读取数据,标题---" + appInfo.getTitle());

                    // 存储数据
                    SharedPreferencesUtils.setParam(MainActivity.this, "appInfo", data);
                    // 保存标题，保存背景图片
                    SharedPreferencesUtils.setParam(MainActivity.this, "title", appInfo.getTitle());
                    SharedPreferencesUtils.setParam(MainActivity.this, "backgroundUrl", appInfo.getBackgroundUrl());

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            setBg();
                            setTitle();
                        }
                    });
                } catch (Exception e) {
                    Log.d(TAG, "----接口返回数据异常---" + e.toString());
                }

            }
        });
    }


//    public native String operationNumberFromJNI(int parameter1, int parameter2, char type);

//    public native int addIntFromCPlusJNI(int parameter1, int parameter2);

//    public native String addStringFromCPlusJNI(String parameter1, String parameter2);

    public native String stringFromJNI();

//    public native int openuart();
    // time 按天算

    /**
     *
     * @param godid       佛灯编号
     * @param name        姓名
     * @param time        时间，天数
     * @param money       金额
     * @param wishstring  祝福内容
     * @param color        1 2 3 4 5 6 7, 默认是1
     * @param language     1 中文; 2 英语， 默认是1
     * @return
     */
    public native int SendMessage(int godid,String name,int time,int money,String wishstring,int color,int language);

    /**
     * 暂时用不上，单独控制某盏佛灯
     * @param lgithid   佛灯编号
     * @param state     佛灯状态
     * @return
     */
    public native int SendCmdLightCtrl(int lgithid, int state);
    // 初始化佛灯
    // startid 起始id，默认从0开始
    // total   总数
    /**
     * 初始化佛灯
     * @param startid  起始id，默认从0开始
     * @param Tatal    佛灯的总数量，例如：500盏佛灯
     * @return
     */
    public native int SendCmdInitSubBoardID(int startid, int Tatal);

    /**
     * 打开所有灯  1
     * 关闭所有灯  0
     * @param state
     * @return
     */
    public native int SendCmdAllLightCtrl(int state);

    /**
     * 单点清屏
     * @param godid  佛像编号
     * @return
     */
    public native int SendCmdClearSingle(int godid);




}